from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.authentication import BasicAuthentication, SessionAuthentication  # 认证
from rest_framework.permissions import IsAuthenticated, AllowAny, IsAdminUser, IsAuthenticatedOrReadOnly  # 权限
from rest_framework.throttling import UserRateThrottle
from rest_framework.filters import OrderingFilter
from rest_framework.pagination import PageNumberPagination
from django.db import DatabaseError

from .models import BookInfo
from .serializers import BookSerializers, PeopleSerializers
"""
路由：和ViewSet定义相同
方法名：不需要自己写，内部封装了create,destroy,update,list,retrieve方法
业务逻辑：只需要指定查询集和序列化器
"""


class StandardPageNumberPagination(PageNumberPagination):
    page_size = 10  # 每页的数目
    page_query_param = 'page_hjt'  # 指定前端发送的页数参数名字
    page_size_query_param = 'page_num'  # 前端请求每页显示多少条数据
    max_page_size = 100  # 后端向前端规定每页最多能显示多少条数据


class Books(ModelViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookSerializers
    authentication_classes = (BasicAuthentication, SessionAuthentication)  # 对该视图做认证
    """
    IsAuthenticated: 是登录用户有权限
    AllowAny: 允许所有用户都有权限
    IsAdminUser:　只有超级管理员用户有权限
    IsAuthenticatedOrReadOnly:　认证用户只有读的权限
    """
    permission_classes = (IsAuthenticated,)  # 对该视图做权限认证

    throttle_classes = (UserRateThrottle, )  # 指定该视图的登录用户访问次数，次数在对应配置文件中的user

    filter_fields = ('name', 'readcount')  # 相当于加入查询字符串参数

    filter_backends = (OrderingFilter, )  # 排序
    ordering_fields = ('commentcount', )  # 查询字符串参数，排序

    pagination_class = StandardPageNumberPagination  # 分页

    # def get_serializer_class(self):
    #     if self.action == 'last_data':
    #         return BookSerializers
    #     elif self.action == 'hero_data':
    #         return PeopleSerializers
    #     else:
    #         raise NotImplemented('没有实现')

    # # 自定义方法
    # @action(methods=['get'], detail=True)  # methods是绑定的请求方法，detail设置为True那么就会生成带pk值的路由，否则不生成
    # def last_data(self, request, pk):
    #     print(self.action)  # 可以重写get_serializer_class方法，通过self.action来取不同的序列化器
    #     book = self.get_object()
    #     ser = self.get_serializer(book)  # get_serializer()方法中调用了get_serializer_class方法来获取序列化器对象
    #
    #     return Response(ser.data)
    def list(self, request, *args, **kwargs):
        raise DatabaseError

        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
